package com.iretailer.quartz.common;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.mapper.TaskMapper;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by xjw
 */
@Service
public class TaskService extends ServiceImpl<TaskMapper, Task> {

    private Logger log = LoggerFactory.getLogger(TaskService.class);

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private QuartzService quartzService;

    /**
     * 暂停一个任务
     *
     * @param id
     * @return
     */
    public boolean pauseJob(String id) {
        boolean status = false;
        int a = taskMapper.updateById(new Task(id, 0));
        if (a > 0) {
            QuartzJobBean quartzJobBean = quartzService.getTask(id);
            status = quartzService.pauseJob(quartzJobBean);
        }
        return status;
    }

    /**
     * 恢复一个任务
     *
     * @param id
     * @return
     */
    public boolean resumeJob(String id) {
        boolean status = false;
        int a = taskMapper.updateById(new Task(id, 1));
        if (a > 0) {
            QuartzJobBean quartzJobBean = quartzService.getTask(id);
            try {
                quartzService.addJob(quartzJobBean);
                status = quartzService.resumeJob(quartzJobBean);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        return status;
    }

    /**
     * 删除一个任务
     *
     * @param id
     * @return
     */
    public boolean deleteJob(String id) {

        boolean status = false;
        int a = taskMapper.updateById(new Task(id, -1));
        if (a > 0) {
            QuartzJobBean quartzJobBean = quartzService.getTask(id);
            status = quartzService.deleteJob(quartzJobBean);
        }
        return status;
    }

    /**
     * 更新时间表达式或者OtherMessage信息
     *
     * @return
     */
    public boolean updateCronExpression(String id, String otherMessage, String cron) {

        boolean status = false;
//        Task bo = taskMapper.selectByPrimaryKey(id);
        Task bo = taskMapper.selectById(id);
        Map<String, Object> message = JSON.parseObject(bo.getOtherMessage(), Map.class);

        Map<String, Object> map = JSON.parseObject(otherMessage, Map.class);
        Set<String> keys = map.keySet();
        for (String key : keys) {
            Object values = message.get(key);
            if (values != null) {
                message.put(key, map.get(key));
            }
        }
        String updateMessage = JSON.toJSONString(message);

        log.debug("====" + updateMessage);

        int a = taskMapper.updateById(new Task(id, cron, updateMessage));
        if (a > 0) {
            QuartzJobBean quartzJobBean = quartzService.getTask(id);
            try {
                quartzService.updateCronExpression(quartzJobBean);
                status = true;
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        return status;
    }


    /*
     *
     * 查询所有的  DateExchangeModuleBO
     * @return
     */
    public List<Task> findAll() {

        List<Task> result = taskMapper.selectList(null);
        for (Task task : result) {
            if (task.getOtherMessage().indexOf("{") > -1) {
                Map<String, Object> message = JSON.parseObject(task.getOtherMessage(), Map.class);
                task.setMessageMap(message);
                task.setOtherMessage("");
            }
        }
        return result;
    }

    /**
     * 立即执行
     *
     * @param id
     * @return
     */
    public boolean testJob(String id) {

        boolean status = false;
        QuartzJobBean quartzJobBean = quartzService.getTask(id);
        if (quartzJobBean != null) {
            try {
                quartzService.testJob(quartzJobBean);
                status = true;
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        return status;
    }

    public QuartzJobBean getQuartzJobBean(String id) {
        QuartzJobBean result = null;
        try {
            QuartzJobBean quartzJobBean = quartzService.getTask(id);
            result = quartzService.getJob(quartzJobBean.getJobName(), quartzJobBean.getJobGroup());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return result;
    }

    public QuartzJobBean getTask(String id) {
        Task bo = taskMapper.selectById(id);
        QuartzJobBean job = null;
        if (bo != null) {
            job = new QuartzJobBean();
            job.setJobId(String.valueOf(bo.getId()));
            job.setJobName(bo.getJobName());
            job.setJobGroup(bo.getJobGroup());
            job.setJobStatus(String.valueOf(bo.getStatus()));//初始状态
            job.setCronExpression(bo.getCron());
            job.setSpringId(bo.getSpringId());
            job.setIsConcurrent(bo.getConcurrent());
            job.setJobClass(bo.getClazzName());
            job.setMethodName(bo.getMethodName());
            job.setDescription(bo.getJobGroup() + "->" + bo.getJobName() + "->" + bo.getDescription());
        }
        return job;
    }

    public Task selectBySpringId(String springId) {
        return taskMapper.selectOne(new QueryWrapper<Task>().lambda().eq(Task::getSpringId, springId));
    }
}

